/**
 * Copyright (C) 2009 Stefan Maassen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package de.indisopht.guice.groovy.spi.internal;

import java.util.Set;

import com.google.inject.Binder;
import com.google.inject.Binding;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.spi.DefaultBindingTargetVisitor;
import com.google.inject.spi.InjectionPoint;
import com.google.inject.spi.ModuleWriter;

/**
 * Module rewriter for examining given bindings and which
 * are related to groovy-guice.
 * 
 * @author Stefan Maassen
 * @since 0.3.0
 */
public class GroovyModuleRewriter extends ModuleWriter {

    /**
     * @see com.google.inject.spi.ModuleWriter#writeBind(com.google.inject.Binder, com.google.inject.Binding)
     */
    @SuppressWarnings("unchecked")
    @Override
    public <T> void writeBind(Binder binder, final Binding<T> binding) {
        final Key<T> key = binding.getKey(); 
        
        binding.acceptTargetVisitor(new DefaultBindingTargetVisitor<T, Void>() {
            @Override
            public Void visitProvider(Provider<? extends T> provider, Set<InjectionPoint> injectionPoints) {
                if (provider instanceof GroovyProvider) {
                    ((GroovyProvider)provider).setBindingType(key.getTypeLiteral().getType());
                }
                return null;
            }
        });
        
        super.writeBind(binder, binding);
    }
}